package com.lijianlove.keeplearning.dr.support.builder;

import com.lijianlove.keeplearning.dr.support.annotation.DR;
import com.lijianlove.keeplearning.dr.support.annotation.DRField;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author lijian
 * @date 2019/4/30 下午2:33
 */
public class KeyBuilder {

    private static String SEPARATOR = "_";

    /**
     * todo lj
     *
     * @param dr
     * @param fields
     * @param param
     * @return
     */
    public String buildKey(DR dr, Field[] fields, Object param) {
        String res = null;
        List<String> calFieldsValue = new ArrayList<>();
        int calBit = dr.calBit();
        if (calBit < 0) {
            return res;
        }
        for (Field field : fields) {
            field.setAccessible(true);
            DRField drField = field.getAnnotation(DRField.class);
            int curFieldBit = drField.value();
            if (Objects.nonNull(drField)) {
                String fieldName = field.getName();
                // todo lj 如果是引用类型 , 并且引用类型中有需要计算的字段
                // 如果存在key 按位与 计算规则，采用按位与
                try {
                    Object fieldValue = field.get(param);
                    if (Objects.nonNull(fieldValue)) {
                        // 按位与>0 幂等验证
                        if (calBit > 0) {
                            if (curFieldBit > 0) {
                                if ((calBit & curFieldBit) == curFieldBit) {
                                    calFieldsValue.add(fieldValue.toString());
                                }
                            }
                        } else {
                            // 如果是 0 按位与 计算规则，所有需要的字段都计算key
                            calFieldsValue.add(fieldValue.toString());
                        }

                    } else {
                        calFieldsValue.add(new NullValue().getValue());
                    }
                } catch (IllegalAccessException e) {
                    calFieldsValue.add(new ExceptionValue().getValue());
                }

            }
        }
        if (calFieldsValue.size() > 0) {
            res=join(calFieldsValue);
        }
        return res;
    }

    private static String join(List<String> calFieldsValue) {
        final StringBuilder buf = new StringBuilder(1 * 16);
        for (int i = 0; i < calFieldsValue.size(); i++) {
            if (i > 0) {
                buf.append(SEPARATOR);
            }
            buf.append(calFieldsValue.get(i));
        }
        return buf.toString();
    }

    private class NullValue {

        public String getValue() {
            return "NULL";
        }
    }

    private class ExceptionValue {

        public String getValue() {
            return "ERR";
        }
    }

}
